package com.flute.icrawler.framework.framework.container;

import java.util.HashMap;

import com.flute.tools.data.berkeleydb.BerkeleyDatabase;
import com.sleepycat.bind.EntryBinding;

public class BerkeleyManager {
	private static HashMap<String, BerkeleyDatabase> databaseMap;

	static {
		databaseMap = new HashMap<String, BerkeleyDatabase>();
	}

	@SuppressWarnings("unchecked")
	/**
	 * 获取数据库 
	 *  env 該數據庫所在的文件夾  即環境名稱
	 */
	public static BerkeleyDatabase getBerkeleyDatabase(String env,
			String dbName, EntryBinding keyBinding, EntryBinding valueBinding) {
		String key = env + "db:" + dbName;
		if (!databaseMap.containsKey(key)) {
			databaseMap.put(key, new BerkeleyDatabase(env, dbName, keyBinding,
					valueBinding));
		}

		return databaseMap.get(key);
	}

	@SuppressWarnings("unchecked")
	public static BerkeleyDatabase getBerkeleyDatabase(String env,
			String dbName, EntryBinding keyBinding) {
		String key = env + "db:" + dbName;
		if (!databaseMap.containsKey(key)) {
			databaseMap.put(key, new BerkeleyDatabase(env, dbName, keyBinding));
		}

		return databaseMap.get(key);
	}

	public static void closeAll() {
		for (BerkeleyDatabase db : databaseMap.values()) {
			db.close();
		}

		databaseMap.clear();
	}

	public static void closeDatabase(BerkeleyDatabase database) {
		String key = null;
		for (String dbKey : databaseMap.keySet()) {
			if (databaseMap.get(dbKey) == database) {
				key = dbKey;
			}
		}

		if (key != null) {
			databaseMap.remove(key);
		}
		database.close();
	}
}
